<?php
namespace app\controller;

use app\BaseController;
use app\model\ExamQuestion;
use app\model\ExamRecord;
use app\model\ExamSession;
use think\facade\View;
use think\facade\Session;

class Exam extends BaseController
{
    // 场次列表
    public function sessionList()
    {
        $sessions = ExamSession::where('status', '<>', 2)
            ->order('start_time', 'desc')
            ->select();
            
        View::assign('sessions', $sessions);
        return View::fetch();
    }
    
    // 开始考试/练习
    public function start($session_id)
    {
        $session = ExamSession::find($session_id);
        if (!$session || $session->status == 2) {
            return redirect('/exam/sessionList')->with('error', '考试场次无效或已结束');
        }
        
        // 检查是否已开始考试
        $record = ExamRecord::where([
            'user_id' => Session::get('user_id'),
            'session_id' => $session_id,
            'status' => 0
        ])->find();
        
        if (!$record) {
            // 创建考试记录
            $record = new ExamRecord();
            $record->user_id = Session::get('user_id');
            $record->session_id = $session_id;
            $record->start_time = date('Y-m-d H:i:s');
            $record->mode = $session->mode;
            
            // 随机组卷
            $questionIds = $this->generateRandomQuestions($session);
            $record->question_ids = json_encode($questionIds);
            $record->save();
        } else {
            $questionIds = json_decode($record->question_ids, true);
        }
        
        // 获取题目
        $questions = ExamQuestion::whereIn('id', $questionIds)
            ->select()
            ->toArray();
        
        // 保持题目顺序
        $orderedQuestions = [];
        foreach ($questionIds as $id) {
            foreach ($questions as $q) {
                if ($q['id'] == $id) {
                    $orderedQuestions[] = $q;
                    break;
                }
            }
        }
            
        View::assign([
            'session' => $session,
            'questions' => $orderedQuestions,
            'record' => $record
        ]);
        return View::fetch();
    }
    
    // 随机组卷算法
    private function generateRandomQuestions($session)
    {
        $rules = json_decode($session->random_rules, true);
        $questionIds = [];
        
        foreach ($rules as $rule) {
            $query = ExamQuestion::where('type', $rule['type']);
            
            if (!empty($rule['difficulty'])) {
                $query->whereIn('difficulty', $rule['difficulty']);
            }
            
            $questions = $query->orderRaw('RAND()')
                ->limit($rule['count'])
                ->column('id');
            
            $questionIds = array_merge($questionIds, $questions);
        }
        
        return $questionIds;
    }
    
    // 提交单题答案（练习模式）
    public function submitQuestion()
    {
        $record_id = input('post.record_id');
        $record = ExamRecord::find($record_id);
        if (!$record || $record->status == 1) {
            return json(['code' => 1, 'msg' => '考试记录无效或已提交']);
        }
        
        $question_id = input('post.question_id');
        $answer = input('post.answer');
        
        $question = ExamQuestion::find($question_id);
        if (!$question) {
            return json(['code' => 1, 'msg' => '题目不存在']);
        }
        
        // 查找或创建答题详情
        $detail = ExamRecordDetail::where([
            'record_id' => $record_id,
            'question_id' => $question_id
        ])->find();
        
        if (!$detail) {
            $detail = new ExamRecordDetail();
            $detail->record_id = $record_id;
            $detail->question_id = $question_id;
        }
        
        $detail->answer = is_array($answer) ? json_encode($answer) : $answer;
        
        // 自动评分
        $result = $this->checkAnswer($question, $answer);
        $detail->is_correct = $result['is_correct'];
        $detail->score = $result['score'];
        
        $detail->save();
        
        return json([
            'code' => 0, 
            'msg' => '提交成功',
            'is_correct' => $result['is_correct'],
            'correct_answer' => $question->answer,
            'explanation' => $question->explanation
        ]);
    }
    
    // 检查答案
    private function checkAnswer($question, $answer)
    {
        $correctAnswer = $question->answer;
        $isCorrect = 0;
        $score = 0;
        
        switch ($question->type) {
            case 1: // 填空
                $isCorrect = (trim($answer) === trim($correctAnswer)) ? 1 : 0;
                break;
            case 2: // 单选
                $isCorrect = ($answer == $correctAnswer) ? 1 : 0;
                break;
            case 3: // 多选
                $correctArr = json_decode($correctAnswer, true);
                sort($correctArr);
                $answerArr = is_array($answer) ? $answer : [$answer];
                sort($answerArr);
                $isCorrect = ($correctArr === $answerArr) ? 1 : 0;
                break;
            case 4: // 判断
                $isCorrect = ($answer == $correctAnswer) ? 1 : 0;
                break;
            case 5: // 简答
                $isCorrect = null;
                break;
        }
        
        $score = $isCorrect ? $question->score : 0;
        
        return [
            'is_correct' => $isCorrect,
            'score' => $score
        ];
    }
}